// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.journeys

import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.content.res.Configuration.UI_MODE_NIGHT_MASK
import android.content.res.Configuration.UI_MODE_NIGHT_UNDEFINED
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import android.graphics.DashPathEffect
import android.graphics.Paint.Cap
import android.graphics.Paint.Join
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.view.View
import android.view.ViewGroup
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.doOnPreDraw
import androidx.core.view.updateLayoutParams
import androidx.core.view.updatePadding
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.sidesheet.SideSheetBehavior
import org.osmdroid.tileprovider.tilesource.TileSourceFactory
import org.osmdroid.util.BoundingBox
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.CustomZoomButtonsController
import org.osmdroid.views.overlay.Marker
import org.osmdroid.views.overlay.Polyline
import org.osmdroid.views.overlay.TilesOverlay
import org.osmdroid.views.overlay.gestures.RotationGestureOverlay
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.data.traffic.Place
import xyz.apiote.bimba.czwek.databinding.ActivityJourneysBinding
import xyz.apiote.bimba.czwek.dpToPixelI
import xyz.apiote.bimba.czwek.repo.Colour
import xyz.apiote.bimba.czwek.repo.JourneyParams
import xyz.apiote.bimba.czwek.repo.Position
import kotlin.math.max
import kotlin.math.min


class JourneysActivity : AppCompatActivity() {
	private lateinit var binding: ActivityJourneysBinding
	private lateinit var journeysViewModel: JourneysViewModel

	companion object {
		const val ORIGIN_PARAM = "origin"
		const val DESTINATION_PARAM = "destination"
		const val PARAMS_PARAM = "params"

		fun getIntent(
			context: Context, origin: Place, destination: Place, params: JourneyParams
		) = Intent(context, JourneysActivity::class.java).apply {
			putExtra(ORIGIN_PARAM, origin as Parcelable)
			putExtra(DESTINATION_PARAM, destination as Parcelable)
			putExtra(PARAMS_PARAM, params)
		}
	}

	private fun getOrigin(): Place = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU) {
		intent.getParcelableExtra(ORIGIN_PARAM, Place::class.java)
	} else {
		@Suppress("DEPRECATION") intent.getParcelableExtra(ORIGIN_PARAM)
	} ?: throw Exception("Origin not given")

	private fun getDestination(): Place = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU) {
		intent.getParcelableExtra(DESTINATION_PARAM, Place::class.java)
	} else {
		@Suppress("DEPRECATION") intent.getParcelableExtra(DESTINATION_PARAM)
	} ?: throw Exception("Destination not given")

	private fun getJourneyParams(): JourneyParams =
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU) {
			intent.getParcelableExtra(PARAMS_PARAM, JourneyParams::class.java)
		} else {
			@Suppress("DEPRECATION") intent.getParcelableExtra(PARAMS_PARAM)
		} ?: throw Exception("Params not given")

	override fun onCreate(savedInstanceState: Bundle?) {
		enableEdgeToEdge()
		super.onCreate(savedInstanceState)
		binding = ActivityJourneysBinding.inflate(layoutInflater)
		setContentView(binding.root)
		journeysViewModel = ViewModelProvider(this)[JourneysViewModel::class.java]

		ViewCompat.setOnApplyWindowInsetsListener(binding.journeys) { v, windowInsets ->
			val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
			val l = windowInsets.displayCutout?.safeInsetLeft?.takeIf { it > 0 } ?: insets.left
			v.updatePadding(bottom = insets.bottom + dpToPixelI(16f), left = l)
			v.updateLayoutParams<ViewGroup.MarginLayoutParams> {
				if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
					topMargin = insets.top + dpToPixelI(16f)
				}
			}
			WindowInsetsCompat.CONSUMED
		}

		binding.map.setTileSource(TileSourceFactory.MAPNIK)
		if (((resources?.configuration?.uiMode
				?: UI_MODE_NIGHT_UNDEFINED) and UI_MODE_NIGHT_MASK) == UI_MODE_NIGHT_YES
		) {
			binding.map.overlayManager.tilesOverlay.setColorFilter(TilesOverlay.INVERT_COLORS)
		}
		binding.map.zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER)
		binding.map.maxZoomLevel = 21.5
		binding.map.minZoomLevel = 5.5
		binding.map.setMultiTouchControls(true)
		binding.map.overlays.add(RotationGestureOverlay(binding.map).apply { isEnabled = true })

		binding.journeys.layoutManager = LinearLayoutManager(this)

		val origin = getOrigin()
		val destination = getDestination()
		val params = getJourneyParams()

		journeysViewModel.journeys.observe(this) {
			binding.journeysProgress.visibility = View.GONE
			if (it.isEmpty()) {
				binding.emptyText.visibility = View.VISIBLE
				binding.emptyImage.visibility = View.VISIBLE
			} else {
				showMarkers(origin.getPosition(), destination.getPosition())

				binding.journeys.visibility = View.VISIBLE

				binding.journeys.adapter = JourneysAdapter(layoutInflater, this, it) { journey, hide ->
					binding.map.overlays.removeAll { true }

					if (hide) {
						showMarkers(origin.getPosition(), destination.getPosition())
						binding.map.invalidate()
						return@JourneysAdapter
					}

					showMarkers(journey.legs[0].origin.getPosition(), journey.legs[0].origin.getPosition())
					showMarkers(
						journey.legs.last().destination.getPosition(), journey.legs.last().destination.getPosition()
					)

					journey.legs.forEachIndexed { i, leg ->
						val shapePoints = leg.shape.map {
							GeoPoint(it.positionLatitude, it.positionLongitude)
						}
						val contrastShape = Polyline()
						val contrastPaint = contrastShape.outlinePaint
						contrastPaint.strokeCap = Cap.ROUND
						contrastPaint.strokeJoin = Join.ROUND
						contrastPaint.color =
							Colour.getThemeColour(com.google.android.material.R.attr.colorOnBackground, this)
						contrastPaint.strokeWidth = contrastPaint.strokeWidth * 1.5f
						contrastShape.setPoints(shapePoints)
						binding.map.overlays.add(contrastShape)

						val shape = Polyline()
						val paint = shape.outlinePaint
						paint.color = leg.start.vehicle.Line.colour.toInt()
						paint.strokeCap = Cap.ROUND
						paint.strokeJoin = Join.ROUND
						if (leg.start.vehicle.Line.kind.isActive()) {
							paint.pathEffect = DashPathEffect(floatArrayOf(10f, 10f), 0f)
							paint.color = Colour.getThemeColour(
								com.google.android.material.R.attr.colorSurfaceContainer, this
							)
						}
						shape.setPoints(shapePoints)
						binding.map.overlays.add(shape)
					}
					binding.map.invalidate()
					zoomMap(
						dpToPixelI(100f),
						BoundingBox(
							max(journey.legs[0].origin.getLatitude(), journey.legs.last().destination.getLatitude()),
							max(journey.legs[0].origin.getLongitude(), journey.legs.last().destination.getLongitude()),
							min(journey.legs[0].origin.getLatitude(), journey.legs.last().destination.getLatitude()),
							min(journey.legs[0].origin.getLongitude(), journey.legs.last().destination.getLongitude()),
						)
					)
				}
			}
		}
		journeysViewModel.getJourneys(this, origin, destination, params)

		val ssb = binding.journeysSideSheet?.let {
			SideSheetBehavior.from<ConstraintLayout>(it)
		}
		ssb?.expand()
	}

	override fun onResume() {
		super.onResume()
		binding.map.doOnPreDraw {
			zoomMap(dpToPixelI(100f))
			val origin = getOrigin()
			val destination = getDestination()
			showMarkers(origin.getPosition(), destination.getPosition())
			binding.map.invalidate()
		}
	}

	fun zoomMap(margin: Int = 0, box: BoundingBox? = null) {
		val origin = getOrigin()
		val destination = getDestination()
		val bb = box ?: BoundingBox(
			max(origin.getLatitude(), destination.getLatitude()),
			max(origin.getLongitude(), destination.getLongitude()),
			min(origin.getLatitude(), destination.getLatitude()),
			min(origin.getLongitude(), destination.getLongitude()),
		)
		binding.map.zoomToBoundingBox(bb, false, margin)
	}

	fun showMarkers(origin: Position, destination: Position) {
		val originMarker = Marker(binding.map).apply {
			position = GeoPoint(origin.positionLatitude, origin.positionLongitude)
			setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
			icon = AppCompatResources.getDrawable(
				this@JourneysActivity, R.drawable.pin
			)
			setOnMarkerClickListener { marker, map ->
				true
			}
		}
		binding.map.overlays.add(originMarker)

		val destinationMarker = Marker(binding.map).apply {
			position = GeoPoint(destination.positionLatitude, destination.positionLongitude)
			setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
			icon = AppCompatResources.getDrawable(
				this@JourneysActivity, R.drawable.pin
			)
			setOnMarkerClickListener { marker, map ->
				true
			}
		}
		binding.map.overlays.add(destinationMarker)
	}
}